// pages/cart/index.js
import {getSetting, openSetting, chooseAddress, showToast, requestPayment} from '../../utils/asyncWx.js';
import regeneratorRuntime from '../../lib/runtime/runtime.js'
import { request } from '../../request/index.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNumber: 0,
    list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    const address = wx.getStorageSync("address")
    let cart = wx.getStorageSync("cart") || []
    // 获取购物车中被选中的商品
    cart = cart.filter(v => v.checked)
    // 计算全选
    // 空数组调用 every 返回值为 true 

    let totalPrice = 0
    let totalNumber = 0
    // 选中了才计算。。。。
    cart.forEach(v => {
      totalPrice += v.goods_price * v.num
      totalNumber += v.num
    })
    this.setData({
      address,
      cart,
      totalPrice,
      totalNumber
    })
  },

  async handleOrderPay () {
    // 1. 判断缓存中有没有token 
    const token = wx.getStorageSync("token")
    // 2. 判断
    if  (!token) {
      wx.navigateTo({
        url: '/pages/auth/index'
      })
      return 
    } else {
      try {
      // 1. 创建订单
      // 2. 准备请求头参数
      const header = { Authorization: token }
      // 3. 准备请求体参数
      const order_price = this.data.totalPrice
      const consignee_addr = this.data.address.all
      const cart = this.data.cart
      let goods = []
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      const orderParams = {order_price, consignee_addr, goods}
      // 4. 发送请求 创建订单 获取订单编号
      const {order_number} = await request({url: '/my/orders/create', method: 'POST', data: orderParams, header: header})
      // 5. 发起预支付接口
      const {pay} = await request({url: '/my/orders/req_unifiedorder', method: 'POST', header, data: {order_number}})
      // 6. 发起微信支付
      await requestPayment(pay)
      // 7. 查询后台订单状态
      const res = await request({url: '/my/orders/chkOrder', method: 'POST', header, data: {order_number}})
      await showToast({
        title: '支付成功'
      })
      // 8.手动删除缓存中已经支付了的商品
      let newCart = wx.getStorageSync('cart')
      newCart = newCart.filter(v => !v.checked)
      wc.getStorageSync('cart', newCart)
      // 8. 支付成功了，跳转到订单页面
      wx.navigateTo({
        url: '/pages/order/index'
      })
      } catch (error) {
        await showToast({
          title: '支付失败'
        })
        
      }
    }
  }



 
  // 支付按钮

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  
})